package com.ruoyi.iot.listener;

import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import net.dreamlu.iot.mqtt.core.client.MqttClientCreator;
import net.dreamlu.iot.mqtt.spring.client.event.MqttConnectedEvent;
import net.dreamlu.iot.mqtt.spring.client.event.MqttDisconnectEvent;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.event.EventListener;
import org.springframework.stereotype.Service;

/**
 * 客户端连接状态监听
 * @Author: 陈江灿
 * @CreateTime: 2025-02-14
 */
@RequiredArgsConstructor
@Service
@Slf4j
public class MqttClientConnectListener {

    @Value("${mqtt.client.client-id}")
    private String clientId;

    @Value("${mqtt.client.user-name}")
    private String userName;

    @Value("${mqtt.client.password}")
    private String password;

    /**
     * 注入MqttClientCreator
     */
    private final MqttClientCreator mqttClientCreator;

    /**
     * 监听MqttConnectedEvent事件
     *
     * @param event
     */
    @EventListener
    public void onConnected(MqttConnectedEvent event) {
        // 打印MqttConnectedEvent信息
        log.info("MqttConnectedEvent:{}", event);
    }

    @EventListener
    public void onDisconnect(MqttDisconnectEvent event) {
        // 离线时更新重连时的密码，适用于类似阿里云 mqtt clientId 连接带时间戳的方式
        log.info("MqttDisconnectEvent:{}", event);
        // 在断线时更新 clientId、username、password
        mqttClientCreator.clientId(clientId + System.currentTimeMillis())
                .username(userName)
                .password(password);
    }
}
